//
//  UserDataChangeViewController.swift
//  GhostWorld
//
//  Created by Jingmei Tan on 2019/12/26.
//  Copyright © 2019 LKGood. All rights reserved.
//

import UIKit
import TextFieldEffects
import Alamofire
import PKHUD

enum UserDataChangeType {
    case HeadImage,NickName,Sex,Phone,Email,Password
}
private let smsTimerInterval: TimeInterval = 60

class UserDataChangeViewController: BaseViewController {
    
    @IBOutlet weak var nickOrEmailView: UIView!
    @IBOutlet weak var phoneView: UIView!
    @IBOutlet weak var sexView: UIView!
    @IBOutlet weak var passwordView: UIView!
    @IBOutlet weak var buttonTopSpace: NSLayoutConstraint!
    
    @IBOutlet weak var nickOrEmailField: HoshiTextField!
    @IBOutlet weak var phoneNumField: HoshiTextField!
    @IBOutlet weak var verificationField: HoshiTextField!
    @IBOutlet weak var sexfield: HoshiTextField!
    @IBOutlet weak var originPasswordFiled: HoshiTextField!
    @IBOutlet weak var firstPasswordField: HoshiTextField!
    @IBOutlet weak var secondPasswordField: HoshiTextField!
    @IBOutlet weak var confirmButton: UIButton!
    @IBOutlet weak var smsButton: UIButton!
    
    @IBOutlet weak var sexSegment: UISegmentedControl!
    
    private var sexSelectIndex = 0
    var type : UserDataChangeType?
    
    private var smsTimer: Timer?
    private var smsCountDown: TimeInterval = 0
    
    
    // MARK:- LifeCycle
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.prepareUI()
        // Do any additional setup after loading the view.
    }
    
    // MARK:- request
    
    private func requestChangeUserInfoWithType() {
        let user = UserManager.shared.currentUser!
        var parameters: Dictionary<String, Any>?
        switch self.type {
        case .NickName:
            guard let userName = self.nickOrEmailField.text?.trim(), userName.isValidChineseIDNumber() else {
                let alert = UIAlertController(title: "昵称不正确", message: "请正确输入中文昵称", cancelTitle: "确定") { _ in
                    self.nickOrEmailField.becomeFirstResponder()
                }
                present(alert, animated: true)
                return
            }
            parameters = [
                "uid":user.identifier,
                "type":"change_display_name",
                "info":userName,
            ]
        case .Sex:
            let genderIndex = self.sexSelectIndex == 11 ? 0 : self.sexSelectIndex == 1 ? 1 : 0
            if genderIndex == user.gender.rawValue {
                HUD.flash(HUDContentType.labeledError(title: "选择不同后，再确认修改", subtitle: nil), delay: 1.5)
                return
            }
            parameters = [
                "uid":user.identifier,
                "type":"change_gender",
                "info":self.sexSelectIndex,
            ]
        case .Phone:
            guard let phone = self.phoneNumField.text?.trim(),
                phone.isValidChineseCellPhoneNumber() else {
                    let alert = UIAlertController(title: "手机号不正确", message: "请重新输入", cancelTitle: "确定") { _ in
                        self.phoneNumField.becomeFirstResponder()
                    }
                    present(alert, animated: true)
                    return
            }
            guard let vcode = self.verificationField.text?.trim(), vcode.count == 6 else {
                let alert = UIAlertController(title: "验证码不正确", message: "请重新输入", cancelTitle: "确定") { _ in
                    self.verificationField.becomeFirstResponder()
                }
                present(alert, animated: true)
                return
            }
            parameters = [
                "uid":user.identifier,
                "type":"change_phone",
                "info":self.phoneNumField.text ?? "",
                "vcode":self.verificationField.text ?? ""
            ]
        case .Email:
            guard let email = self.nickOrEmailField.text?.trim(), email.isValidEmail() else {
                let alert = UIAlertController(title: "邮箱不正确", message: "请重新输入", cancelTitle: "确定") { _ in
                    self.nickOrEmailField.becomeFirstResponder()
                }
                present(alert, animated: true)
                return
            }
            parameters = [
                "uid":user.identifier,
                "type":"change_email",
                "info":self.nickOrEmailField.text ?? "",
            ]
        case .Password:
            guard let originPassword = self.originPasswordFiled.text,
              originPassword.count > 0 else {
                let alert = UIAlertController(title: "原密码不能为空", message: "", cancelTitle: "确定") { _ in
                    self.originPasswordFiled.becomeFirstResponder()
                }
                present(alert, animated: true)
                return
            }
            guard let password = self.firstPasswordField.text,
              password.count > 0 else {
                let alert = UIAlertController(title: "新密码不能为空", message: "", cancelTitle: "确定") { _ in
                    self.firstPasswordField.becomeFirstResponder()
                }
                present(alert, animated: true)
                return
            }
            guard let confirmPassword = secondPasswordField.text,
              confirmPassword.count > 0 else {
                let alert = UIAlertController(title: "请再次输入密码", message: "请重新输入", cancelTitle: "确定") { _ in
                    self.secondPasswordField.becomeFirstResponder()
                }
                present(alert, animated: true)
                return
            }
            
            guard confirmPassword == password else {
                let alert = UIAlertController(title: "两次密码输入不一致", message: "请重新输入", cancelTitle: "确定") { _ in
                }
                present(alert, animated: true)
                return
            }
            parameters = [
                "uid":user.identifier,
                "type":"change_pwd",
                "oldpwd":self.originPasswordFiled.text ?? "",
                "info":self.firstPasswordField.text ?? "",
            ]
        default: return
            
        }
        
        HUD.show(HUDContentType.labeledProgress(title: "请稍后。。", subtitle: nil))
        API.requsetPost(APIURLStrings.userInfoCheck, parameters: parameters!, success: { (result) in
            let status = result["status"].intValue
            let msg = result["msg"].string
            
            if status == 1 {
                switch self.type {
                case .NickName: //修改昵称
                    if let name = result["data"]["display_name"].string {
                        UserManager.shared.currentUser?.nickname = name
                        UserManager.shared.updateUserDefault()
                        NotificationCenter.default.post(name: .updateUserInfo, object: [UserDataChangeType.NickName:name])
                        HUD.flash(HUDContentType.labeledSuccess(title:msg, subtitle: nil), delay: 1.5)
                    }
                    else{
                        HUD.flash(HUDContentType.labeledError(title:msg, subtitle: nil), delay: 1.5)
                        return
                    }
                case .Sex: //修改性别
                    let sex = result["data"]["gender"].intValue
                    UserManager.shared.currentUser?.gender = sex == 11 ? User.Gender.unknown : sex == 1 ? User.Gender.male : User.Gender.female
                    UserManager.shared.updateUserDefault()
                    NotificationCenter.default.post(name: .updateUserInfo, object: [UserDataChangeType.Sex:sex])
                    HUD.flash(HUDContentType.labeledSuccess(title:msg, subtitle: nil), delay: 1.5)
                case .Phone: //修改电话
                    let phoneNum = result["data"]["phone"].string
                    UserManager.shared.currentUser?.cellPhone = phoneNum
                    NotificationCenter.default.post(name: .updateUserInfo, object: [UserDataChangeType.Phone:phoneNum])
                    HUD.flash(HUDContentType.labeledSuccess(title:msg, subtitle: nil), delay: 1.5)
                case .Email: //修改邮箱
                    let email = result["data"]["email"].string
                    UserManager.shared.currentUser?.email = email
                    NotificationCenter.default.post(name: .updateUserInfo, object: [UserDataChangeType.Email:email])
                    HUD.flash(HUDContentType.labeledSuccess(title:msg, subtitle: nil), delay: 1.5)
                case .Password: //修改密码
                    HUD.flash(HUDContentType.labeledSuccess(title:msg, subtitle: nil), delay: 1.5)
                default: break
                }
                
                DispatchQueue.main.asyncAfter(deadline: .now() + 1.5) {
                    let controller = (self.navigationController?.viewControllers.reversed()[1])!
                    self.navigationController?.popToViewController(controller, animated: true)
                }
                
            }
            else {
                HUD.flash(HUDContentType.labeledError(title:msg, subtitle: nil), delay: 1.5)
            }
        }) { (error) in
            HUD.hide()
            print(error.localizedDescription)
        }
    }
    
    //获取验证码
    private func requstIdentifyCode() {
        guard let phone = self.phoneNumField.text?.trim(),
            phone.isValidChineseCellPhoneNumber() else {
                let alert = UIAlertController(title: "手机号不正确", message: "请重新输入", cancelTitle: "确定") { _ in
                    self.phoneNumField.becomeFirstResponder()
                }
                present(alert, animated: true)
                return
        }
        
        HUD.show(.labeledProgress(title: "请稍后", subtitle: nil))
        let body = ["phone": phone]
        API.requsetPost(APIURLStrings.messageSend, parameters: body, success: { (json) in
            HUD.flash(.labeledSuccess(title: "验证码已发送", subtitle: "请查收短信"), delay: 1.5)
            let code = "\(json["data"]["vcode"].intValue)"
            self.verificationField.text = code
            self.smsTimer?.invalidate()
            self.smsCountDown = smsTimerInterval
            self.smsButton.isEnabled = false
            self.smsTimer = Timer.scheduledTimer(withTimeInterval: 1, repeats: true, block: { timer in
                if self.smsCountDown > 0 {
                    self.smsButton.setTitle("\(Int(self.smsCountDown))s", for: .normal)
                    self.smsCountDown -= 1
                } else {
                    timer.invalidate()
                    self.smsButton.setTitle("获取验证码", for: .normal)
                    self.smsButton.isEnabled = true
                }
            })
        }){ (error) in
            HUD.flash(.labeledError(title: "请求失败", subtitle: "请重试"), delay: 1.5)
        }
    }
    
    
    //MARK: - UI
    private func prepareUI() {
        switch self.type {
        case .NickName,.Email:
            self.nickOrEmailView.isHidden = false
            self.buttonTopSpace.constant = 140
            self.nickOrEmailField.placeholder = self.type == .NickName ? "昵称" : "邮箱"
            if self.type == UserDataChangeType.NickName {
                self.nickOrEmailField.text = UserManager.shared.currentUser!.nickname
            }
        case .Sex:
            self.sexView.isHidden = false
            self.buttonTopSpace.constant = 140
            let user = UserManager.shared.currentUser;
            switch user!.gender {
            case .male:
                self.sexfield.text = "男"
                self.sexSegment.selectedSegmentIndex = 1
                self.sexSelectIndex = 1
            case .female:
                self.sexfield.text = "女"
                self.sexSegment.selectedSegmentIndex = 0
                self.sexSelectIndex = 2
            case .unknown:
                self.sexfield.text = "保密"
                self.sexSegment.selectedSegmentIndex = 2
                self.sexSelectIndex = 11
            }
            self.sexfield.isUserInteractionEnabled = false
        case .Phone:
            self.phoneView.isHidden = false
            self.buttonTopSpace.constant = 260
        case .Password:
            self.passwordView.isHidden = false
            self.buttonTopSpace.constant = 260
            self.originPasswordFiled.isSecureTextEntry = true
            self.firstPasswordField.isSecureTextEntry = true
            self.secondPasswordField.isSecureTextEntry = true
        default: break
        }
    }
    
    //MARK: - Action
    //确认修改
    @IBAction func actionConfirmButton(_ sender: UIButton) {
        self.view.endEditing(true)
        
        self.requestChangeUserInfoWithType()
    }
    //性别选择
    @IBAction func actionSexSelect(_ sender: UISegmentedControl) {
        let selectIndex = sender.selectedSegmentIndex
        
        switch selectIndex {
        case 0:
            self.sexfield.text = "女"
            self.sexSelectIndex = 2
        case 1:
            self.sexfield.text = "男"
            self.sexSelectIndex = 1
        case 2:
            self.sexfield.text = "保密"
            self.sexSelectIndex = 11
        default:break
        }
    }
    //点击收回键盘
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        self.view.endEditing(true)
    }
    //获取验证码
    @IBAction func actionSendSms(_ sender: UIButton) {
        self.view.endEditing(true)
        self.requstIdentifyCode()
    }
    
    // MARK: - Navigation
    
    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        
    }
}
